import router from "./router";
import store from "./store";
import NProgress from "nprogress"; // Progress 进度条
import "nprogress/nprogress.css"; // Progress 进度条样式
import utils from "./utils/utils";
import Vue from "vue";
const _import = require("./router/_import_" + process.env.NODE_ENV);
import Layout from "./views/layout/Layout";
import {
  getToken,
  setToken,
  removeToken,
  setTokenName
} from "@/utils/auth";
import {
  debuglog
} from "util";
// permissiom judge
function hasPermission(roles, permissionRoles) {
  if (roles.indexOf("admin") >= 0) return true; // admin权限 直接通过
  if (!permissionRoles) return true;
  return roles.some(role => permissionRoles.indexOf(role) >= 0);
}
// register global progress.
const whiteList = ["/login", "/authredirect"]; // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start(); // 开启Progress
  if (getToken()) {
    // 判断是否有token
    if (to.path === "/login") {
      next({
        path: "/"
      });
    } else {
      const userData = JSON.parse(Vue.localStorage.get("userRouter"));
      const storeRouter = store.getters.addRouters;
      if (storeRouter.length === 0) {
        store.dispatch("GenerateRoutes", {
          userData
        })
          .then(() => {
            router.addRoutes(store.getters.addRouters);
            next({
              ...to,
              replace: true
            });
          });
      } else {
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      if (utils.showPwdPage) {
        next("/login"); // 否则全部重定向到登录页
        NProgress.done(); // 在hash模式下 改变手动改变hash 重定向回来 不会触发afterEach 暂时hack方案 ps：history模式下无问题，可删除该行！
      } else {
        // var d = {
        //   LoginName: "admin",
        //   pwd: "zhd2017"
        // };
        // var data = utils.getUserInfo(d.LoginName);
        // var roles = [];
        // roles.push(data.role);
        // store
        //   .dispatch("GenerateRoutes", {
        //     roles
        //   })
        //   .then(() => {
        //     // 生成可访问的路由表
        //     router.addRoutes(store.getters.addRouters); // 动态添加可访问路由表
        //     // hack方法 确保addRoutes已完成
        //   });
        // setToken(data.token);
        // setTokenName(data.name);
        // store.commit("SET_ROLES", data.role);
        // store.commit("SET_NAME", data.name);
        // store.commit("SET_UERINFO", this.loginForm);
        // store.commit("SET_TOKEN", data.token);
        // store.commit("SET_AVATAR", data.avatar);
        // store.commit("SET_INTRODUCTION", data.introduction);
        next("/");
      }
    }
  }
});

router.afterEach(() => {
  NProgress.done(); // 结束Progress
});
